#!/bin/sh
#
# rc Script for configure networks.
# (c) dangbinghoo@gmail.com. playpenguin.org
#

. /etc/conf.d/net
. /etc/init.d/rcfunctions

netdevconf()
{
	local link=`eval echo \$"${1}_link"`
	
	if [ "$link"=="static" ];then
		local macaddr=`eval echo \$"${1}_mac"`
		rc_echo
		rc_echo "   - MAC     : $macaddr"

		if [ "$macaddr"!="" ];then
			ifconfig $ndev hw ether "${macaddr}"
		fi

		local ipaddr=`eval echo \$"${1}_ip"`
		rc_echo "   - IP      : $ipaddr"
		local netmask=`eval echo \$"${1}_netmask"`
		rc_echo "   - Netmask : $netmask"
		local gateway=`eval echo \$"${1}_gateway"`
		rc_echo "   - gateway : $gateway"
		ifconfig $ndev $ipaddr netmask $netmask
		
		if [ "$gataway"!="" ];then
			route add default gw $gateway
		fi
	elif  [ "$link"=="dhcp" ];then
		rc_echo " !${1} is configred using dhcp"
		udhcpc -i ${1}
	fi
}

checkdev()
{
	local dirn=`echo $0|xargs dirname`
	local scrptn=`echo $0|sed -e 's|/etc/init.d/||'`
	
	ndev=`echo $scrptn|awk -F '.' '{print $2}'`
	
	if [ -z "$ndev" ];then
		rc_error  " Error , you need to make a link to "
		rc_error  " etc/init.d/network.\$dev and call the linked script."
		rc_error  " for ex.\"/etc/init.d/network.eth0\""
     		rc_status "${WN_msg}"
		exit 1
	fi

	export  $ndev
}

start() {	
	ifconfig $ndev down
	rc_do_msg "Configuring network dev \"$ndev\"..."
	netdevconf $ndev
	ifconfig $ndev up
	ifconfig lo up
	
	# DNS server
     	echo "# Generated by /etc/init.d/network script" > /etc/resolv.conf
     	echo "nameserver $nameserver" >> /etc/resolv.conf
     	rc_status "${OK_msg}"
     	sleep 3
}

restart()
{
	stop
	start $ndev
}

stop()
{
     	rc_do_msg "Restarting network dev $ndev"
     	ifconfig $ndev down
     	ifconfig lo down
     	echo "# Generated by /etc/init.d/network script" > /etc/resolv.conf
     	rc_status "${DE_msg}"
}


# main
checkdev

case "$1" in
	"start")
		start $ndev;;
	"stop")	
		stop;;
	"restart")
		restart;;
	*)
		echo "Usage: $0 start|stop|restart"
		exit 0
esac

unset $ndev
		
	
